package com.ctos.ojbackendquestionservice.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import static com.ctos.ojbackendcommon.constant.RabbitMqConstant.*;

/**
 * 用于创建测试程序用到的交换机和队列（只用在程序启动前执行一次）
 */
@Slf4j
public class InitMq {
    public static void Init(){
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(RABBITMQ_IPADDR);
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            String EXCHANGE_NAME = JUDGE_QUESTION_EXCHANGE_NAME;
            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            // 创建队列，随机分配一个队列名称
            String queueName = JUDGE_QUESTION_QUEUE_NAME;
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, EXCHANGE_NAME, JUDGE_QUESTION_ROUTING_KEY);
            log.info("Queue created successfully");
        } catch (Exception e) {
            log.error("交换机队列初始化失败:"+e);
        }
    }
}
